Object class
C# defines one special class called object that is an implicit base class of all other classes and for all other types. object is a base class for all other types and that boxing of the value types takes place automatically, it is possible to use object as a “universal” data type.
Object class methods
Method |
Purpose |
public virtual bool Equals(object ob) |
Determines whether the invoking object is the same as the one referred to by ob. |
public static bool Equals(object ob1, object ob2) |
Determines whether ob1 is the same as ob2. |
protected Finalize( ) |
Performs shutdown actions prior to garbage collection. In C#, Finalize( ) is accessed through a destructor. |
public virtual int GetHashCode( ) |
Returns the hash code associated with the invoking object. |
public Type GetType( ) |
Obtains the type of an object at runtime. |
protected object MemberwiseClone( ) |
Makes a “shallow copy” of the object. (The members are copied, but objects referred to by members are not.) |
public static bool ReferenceEquals(object ob1, object ob2) |
Determines whether ob1 and ob2 refer to the same object. |
public virtual string ToString( ) |
Returns a string that describes the object |
Boxing and Unboxing
object is a base class for all other types and that boxing of the value types takes place automatically, it is possible to use object as a “universal” data type.
When an object reference refers to a value type, a process known as boxing occurs. Boxing causes the value of a value type to be stored in an object instance. Thus, a value type is “boxed” inside an object. This object can then be used like any other object. In all cases, boxing occurs automatically. You simply assign a value to an object reference.
Unboxing is the process of retrieving a value from a boxed object. This action is performed using an explicit cast from the object reference to its corresponding value type. Attempting to unbox an object into a different type will result in a runtime error.
Program on boxing
using System;
class Sample
{
public static void Main(String[] args)
{
int a = 10;
object x;
x = a; // boxing
int k =(int) x;//unboxing
Console.WriteLine("Value of k after unboxing" + k);
}
}
Program to find the factorial values using boxing and unboxing
using System;
class Sample
{
public static void Main(String[] args)
{
int a;
Console.WriteLine("Enter no");
a =Convert.ToInt32 ( Console.ReadLine());
Console.WriteLine("Factorial" + fact(a));
}
public static int fact(object x)
{
int f = 1;
for (int i = 1; i <= (int)x; i++)
{
f = f * i;
}
return f;
}
}